package com.koudai.reader.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;

import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;
import com.koudai.reader.vo.Task;
import com.mj.util.MD5Checksum;

public class HttpUtils {

    private static String HOST = "http://121.199.45.209/index.php";

    final private static String API_URL_USERINFO = "user.getUser";
    final private static String API_URL_SEARCH = "search.searchByTerm";
    final private static String API_URL_TOP = "search.top";
    final private static String API_URL_LIST_BY_CATE = "search.getListByCate";
    final private static String API_URL_CATE_LIST = "search.getCateList";
    final private static String API_URL_BOOKSHELF_ADD = "bookshelf.add";
    final private static String API_URL_BOOKSHELF_DET = "bookshelf.det";
    final private static String API_URL_BOOKSHELF_LIST = "bookshelf.bookList";
    final private static String API_URL_BOOKSHELF_UPDATE = "bookshelf.bookupdate";
    final private static String API_URL_GOLD_OP = "gold.op";
    final private static String API_URL_GOLD_OP_WALL = "gold.opWall";
    final private static String API_URL_GOLD_OP_GOLD_VIP = "gold.opGoldVip";
    final private static String API_URL_TASK_CREATE = "task.create";
    final private static String API_URL_TASK_DELETE = "task.delete";
    final private static String API_URL_TASK_TASKLIST = "task.taskList";
    final private static String API_URL_GET_TERM = "term.getTermList";
    final private static String API_URL_SUBMIT_REQUEST = "task.addFeedback";

    public static void main(String[] args) {
        searchByTerm("凡人修仙传");
    }

    public static String generateToken(long time) {
        String result = null;
        try {
            char[] targetArray = MD5Checksum.getChecksum4String(String.valueOf(time)).toCharArray();
            char[] randomArray1 = UUID.randomUUID().toString().toCharArray();
            char[] randomArray2 = UUID.randomUUID().toString().toCharArray();

            StringBuilder tmpArray = new StringBuilder();
            for (int i = 0; i < 32; i++) {
                tmpArray.append(targetArray[i]).append(randomArray1[i]).append(randomArray2[i]);
            }
            if (tmpArray.length() == 96) {
                result = tmpArray.substring(48, 96) + tmpArray.substring(0, 48);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static boolean submitRequest (String content, Context context) {
        try {
            
            
            TelephonyManager phoneMgr=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_SUBMIT_REQUEST));
            params.add(new BasicNameValuePair("d", EndUser.getInstance().getDeviceid()));
            params.add(new BasicNameValuePair("content", content));
            params.add(new BasicNameValuePair("title", String.valueOf(EndUser.getInstance().getVersion())));
            params.add(new BasicNameValuePair("qq", phoneMgr.getLine1Number()));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));
            
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    
                    
                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static boolean gold2VIP() {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_GOLD_OP_GOLD_VIP));
            params.add(new BasicNameValuePair("device_id", EndUser.getInstance().getDeviceid()));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {

                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static boolean addGold4user(int gold) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_GOLD_OP_WALL));
            params.add(new BasicNameValuePair("device_id", EndUser.getInstance().getDeviceid()));
            params.add(new BasicNameValuePair("g", String.valueOf(gold)));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {

                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static boolean goldOperation(String action) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_GOLD_OP));
            params.add(new BasicNameValuePair("device_id", EndUser.getInstance().getDeviceid()));
            params.add(new BasicNameValuePair("a", action));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {

                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static List<Task> taskList() {

        List<Task> result = new ArrayList<Task>();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_TASK_TASKLIST));
            params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {

                    result.addAll(JsonUtil.convertTasklist(responseJson.getJSONArray("list")));
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    public static boolean delTask(String taskId) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_TASK_DELETE));
            params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
            params.add(new BasicNameValuePair("id", taskId));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static boolean addTask(String term) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_TASK_CREATE));
            params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
            params.add(new BasicNameValuePair("term", term));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static List<Book> updateBookshelf(List<Integer> bookids) throws Exception {

        List<Book> result = new ArrayList<Book>();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("do", API_URL_BOOKSHELF_UPDATE));
        params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
        long time = Calendar.getInstance().getTimeInMillis();
        params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
        params.add(new BasicNameValuePair("token", generateToken(time)));

        if (bookids != null && bookids.size() > 0) {
            StringBuilder sb = new StringBuilder();

            for (Integer item : bookids) {
                sb.append(item + ",");
            }

            params.add(new BasicNameValuePair("bids", sb.substring(0, sb.length() - 1)));
        }

        HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        final HttpPost post = new HttpPost(HOST);
        post.setEntity(entity);

        HttpResponse httpResponse = getHttpClient().execute(post);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject responseJson = getJsonObject(httpResponse);
            if (responseJson.getString("status").equals("success")) {

                result.addAll(JsonUtil.convertUpdateBooklist(responseJson.getJSONArray("list")));
            }

        }

        return result;
    }

    public static boolean delBookshelf(int bookid) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_BOOKSHELF_DET));
            params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
            params.add(new BasicNameValuePair("bid", String.valueOf(bookid)));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static boolean addBookshelf(int bookid) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_BOOKSHELF_ADD));
            params.add(new BasicNameValuePair("uid", EndUser.getInstance().getUid()));
            params.add(new BasicNameValuePair("bid", String.valueOf(bookid)));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    return true;
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    public static void categoryList() {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_CATE_LIST));

            final HttpPost post = new HttpPost(HOST);

            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    JsonUtil.convertAllCategory(responseJson.getJSONArray("list"));
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static List<Book> getListByCate(String cateName, int start) throws Exception {

        List<Book> result = new ArrayList<Book>();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("do", API_URL_LIST_BY_CATE));
        params.add(new BasicNameValuePair("cate", String.valueOf(Constant.allCategoryMapping.get(cateName))));
        params.add(new BasicNameValuePair("i", String.valueOf(start)));
        long time = Calendar.getInstance().getTimeInMillis();
        params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
        params.add(new BasicNameValuePair("token", generateToken(time)));

        HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        final HttpPost post = new HttpPost(HOST);
        post.setEntity(entity);

        HttpResponse httpResponse = getHttpClient().execute(post);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject responseJson = getJsonObject(httpResponse);
            if (responseJson.getString("status").equals("success")) {
                result = JsonUtil.convertBooklist(responseJson.getJSONArray("list"));
            }

        }

        return result;
    }

    public static List<Book> searchTop(int categoryId) throws Exception {

        List<Book> result = new ArrayList<Book>();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("do", API_URL_TOP));
        params.add(new BasicNameValuePair("c", String.valueOf(categoryId)));
        long time = Calendar.getInstance().getTimeInMillis();
        params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
        params.add(new BasicNameValuePair("token", generateToken(time)));

        HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        final HttpPost post = new HttpPost(HOST);
        post.setEntity(entity);

        HttpResponse httpResponse = getHttpClient().execute(post);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject responseJson = getJsonObject(httpResponse);
            if (responseJson.getString("status").equals("success")) {
                result = JsonUtil.convertBooklist(responseJson.getJSONArray("list"));
                if (!responseJson.isNull("cateList")) {
                    JsonUtil.convertMainCategory(responseJson.getJSONObject("cateList"));
                }

            }

        }

        return result;
    }

    public static String getTerm(String type) {

        String result = null;
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_GET_TERM));
            params.add(new BasicNameValuePair("t", type));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    result = JsonUtil.convertTermlist(responseJson.getJSONArray("list"));
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    public static List<Book> searchByTerm(String term) {

        List<Book> result = new ArrayList<Book>();

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_SEARCH));
            params.add(new BasicNameValuePair("t", term));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    result = JsonUtil.convertBooklist(responseJson.getJSONArray("list"));
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    public static void requestUserinfo(Context context) throws Exception {

        try {

            SharedPreferences config = context.getSharedPreferences("config", 0);
            HOST = config.getString("host", "http://121.199.45.209/index.php");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("do", API_URL_USERINFO));
            params.add(new BasicNameValuePair("device_id", EndUser.getInstance().getDeviceid()));
            long time = Calendar.getInstance().getTimeInMillis();
            params.add(new BasicNameValuePair("server_t", String.valueOf(time)));
            params.add(new BasicNameValuePair("token", generateToken(time)));

            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                JSONObject responseJson = getJsonObject(httpResponse);
                if (responseJson.getString("status").equals("success")) {
                    JsonUtil.convert2UserInfo(responseJson.getJSONObject("info"));
                    String host = responseJson.getString("host");

                    config.edit().putString("host", "http://" + host + "/index.php");
                }

            }
        } catch (Exception e) {

            e.printStackTrace();
            // TODO Auto-generated catch block
            throw new Exception();

        }
    }

    private static JSONObject getJsonObject(HttpResponse httpResponse) throws IOException, JSONException {
        String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        JSONObject responseJson = new JSONObject(response);
        return responseJson;
    }

    /**
     * Configures the httpClient to connect to the URL provided.
     */
    public static HttpClient getHttpClient() {
        HttpClient httpClient = new DefaultHttpClient();

        final HttpParams params = httpClient.getParams();
        // 设置网络与服务器建立连接的超时时间,即socket连接的超时时间(3sec)
        HttpConnectionParams.setConnectionTimeout(params, Constant.HTTP_REQUEST_TIMEOUT_MS);
        // Socket读数据的超时时间，即从服务器获取响应数据需要等待的时间
        HttpConnectionParams.setSoTimeout(params, Constant.HTTP_REQUEST_TIMEOUT_MS);
        // // ConnectionManager管理的连接池中取出连接的超时时间
        // ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);

        return httpClient;
    }
}
